/*
    SDL - Simple DirectMedia Layer
    Copyright (C) 1997-2009 Sam Lantinga

    This library is free software; you can redistribute it and/or
    modify it under the terms of the GNU Lesser General Public
    License as published by the Free Software Foundation; either
    version 2.1 of the License, or (at your option) any later version.

    This library is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
    Lesser General Public License for more details.

    You should have received a copy of the GNU Lesser General Public
    License along with this library; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/
#include "SDL_cellvideo.h"
#include "../../events/SDL_events_c.h"
#include <sysutil/sysutil_common.h>

/* PS3 callback */
static void						sysutil_callback					(uint64_t status, uint64_t param, void *userdata)
{
	switch(status)
	{
		case CELL_SYSUTIL_REQUEST_EXITGAME:		CELL_Video.Events.WantToDie = 1; break;
		case CELL_SYSUTIL_SYSTEM_MENU_OPEN:		CELL_Video.Events.WantToSleep = 1; break; 
		case CELL_SYSUTIL_SYSTEM_MENU_CLOSE:	CELL_Video.Events.WantToSleep = 0; break;
	}
}

/* SDL Functions */
void							CELL_EVENTS_Pump					(_THIS)
{
	/* Only pump every 15 milliseconds, prevents deadlock with mouse motion events */
	uint32_t newtime = SDL_GetTicks();
	if(newtime - CELL_Video.Events.LastPump > 15)
	{
		CELL_MOUSE_Process();
		CELL_KEYBOARD_Process();
		CELL_PAD_ProcessByMode();

		CELL_Video.Events.LastPump = newtime;
	}

	if(newtime - CELL_Video.PSGLState.RefreshTime > 30)
	{
		CELL_PSGL_Update(this);
	}

	/* Check for xmb stuff */
	do
	{
		cellSysutilCheckCallback();
		if(CELL_Video.Events.WantToDie)
		{
			SDL_PrivateQuit();
			CELL_Video.Events.WantToDie = 0;	
			CELL_Video.Events.WantToSleep = 0;
			break;
		}

		if(CELL_Video.Events.WantToSleep)
		{
			CELL_PSGL_Update(CELL_VideoDevice);
		}
	}	while(CELL_Video.Events.WantToSleep);
}

void							CELL_EVENTS_Init					(_THIS)
{
	/* Register callback */
	cellSysutilRegisterCallback(0, (CellSysutilCallback)sysutil_callback, NULL);
}

